//
//  MessageTalkViewController.m
//  WalkerKitProject
//
//  Created by JingCheng on 15/7/11.
//  Copyright (c) 2015年 景铖. All rights reserved.
//

#import "MessageTalkViewController.h"
#import "AllHeader.h"
#import "UUInputFunctionView.h"
#import "UUMessageCell.h"
#import "UUMessageFrame.h"
#import "UUMessage.h"
#import "MJRefresh.h"
#import "ChatModel.h"


@interface MessageTalkViewController ()<UUInputFunctionViewDelegate,UUMessageCellDelegate,UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) MJRefreshHeaderView *head;
@property (strong, nonatomic) ChatModel *chatModel;
@property (strong, nonatomic)  UITableView *chatTableView;
@property (strong, nonatomic)  NSLayoutConstraint *bottomConstraint;
@end

@implementation MessageTalkViewController
{
    UUInputFunctionView *IFView;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.barTintColor = kCustomColor(255, 255, 255, 1);
//    self.view.backgroundColor = [UIColor redColor]
    
    //自定义导航栏
    [self creactBarButtonItem];
    //返回上一个页面
    [self popAfterPage];
    //添加背景颜色
    [self addBackgroundColor];
    //添加聊天界面
    [self creactTableViewMessage];
    //下拉刷新数据
    [self addRefreshViews];
    //每次发一条新的消息，界面会自动向上滚动消息内容的高度
    [self loadBaseViewsAndData];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

/**
 *  键盘发生改变执行
 */
- (void)keyboardWillChange:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    
    CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat moveY = keyFrame.origin.y - self.view.frame.size.height;
    
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
    }];
}
/**
 *  自定义导航栏
 */
- (void)creactBarButtonItem
{
    //设置导航栏的颜色
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    //创建左边导航栏的样式
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_barButtonItem"] style:(UIBarButtonItemStylePlain) target:self action:@selector(tapToBack:)];
    
    [self.navigationController.navigationItem setLeftBarButtonItem:backBarButton];
    
    self.navigationItem.leftBarButtonItem = backBarButton;
}

/**
 *  添加返回上一个页面的手势
 */
- (void)popAfterPage
{
    UISwipeGestureRecognizer *backSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tapToBack:)];
    [backSwipeGestureRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.view addGestureRecognizer:backSwipeGestureRecognizer];
}

//返回上一个页面执行的时间
- (void)tapToBack:(UIBarButtonItem *)barbuttom
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  添加背景颜色
 */
- (void)addBackgroundColor
{
    _backgroundImage = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _backgroundImage.backgroundColor = kBackgroundColor;
    [self.view addSubview:_backgroundImage];
}

/**
 *  创建聊天界面
 */
- (void)creactTableViewMessage
{
    //设置头标题
    self.navigationItem.title = @"Jams Bound";
    
    _chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , SCREEN_HEIGHT - 44) style:(UITableViewStylePlain)];
    _chatTableView.dataSource = self;
    _chatTableView.delegate = self;
    _chatTableView.rowHeight = 44;
    _chatTableView.sectionHeaderHeight = 22;
    _chatTableView.sectionFooterHeight = 22;
    [_chatTableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    _chatTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_chatTableView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  通知是否发送消息，如成功发送消息，则会弹出出入框和发送的按钮
 */
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //通知来获得当键盘改变时，该键盘的高度和位置。
    //然后调整自己相应的UI元素位置即可
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    
    //当焦点离开可输入的控件时，键盘会自动隐藏，并且触发UIKeyboardWillHideNotification通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tableViewScrollToBottom) name:UIKeyboardDidShowNotification object:nil];
}

-(void)keyboardChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    

    
    
    //adjust ChatTableView's height
    if (notification.name == UIKeyboardWillShowNotification) {
        self.bottomConstraint.constant = keyboardEndFrame.size.height+40;
    }else{
        self.bottomConstraint.constant = 40;
    }
    
    [self.view layoutIfNeeded];
    
    //adjust UUInputFunctionView's originPoint
    CGRect newFrame = IFView.frame;
//    newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;
    IFView.frame = newFrame;
    
    [UIView commitAnimations];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/**
 *  下拉刷新数据
 */
- (void)addRefreshViews
{
    __weak typeof(self) weakSelf = self;
    
    //load more
    int pageNum = 3;
    
    _head = [MJRefreshHeaderView header];
    _head.scrollView = self.chatTableView;
    _head.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        [weakSelf.chatModel addRandomItemsToDataSource:pageNum];
        
        if (weakSelf.chatModel.dataSource.count > pageNum) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:pageNum inSection:0];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.chatTableView reloadData];
                [weakSelf.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            });
        }
        [weakSelf.head endRefreshing];
    };
}

- (void)loadBaseViewsAndData
{
    //设置用户头像和设置聊天内容
    self.chatModel = [[ChatModel alloc]init];
    self.chatModel.isGroupChat = NO;
    [self.chatModel populateRandomDataSource];
    
    /**
     自定义聊天页面的键盘
     */
    IFView = [[UUInputFunctionView alloc]initWithSuperVC:self];
    IFView.delegate = self;
    [self.view addSubview:IFView];
    
    //刷新页面
    [self.chatTableView reloadData];
    [self tableViewScrollToBottom];
}

/**
 *  每次发一条新的消息，界面会自动向上滚动消息内容的高度
 */
- (void)tableViewScrollToBottom
{
    //如果数据内容为空，就返回，不需要滚动
    if (self.chatModel.dataSource.count==0)
        return;
    //返回索引路径对象使用的特定的行和在表视图中的部分指标进行初始化
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.dataSource.count - 1 inSection:0];
    
    //把当前行滚动到指定位置
    [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


#pragma mark - InputFunctionViewDelegate
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message
{
    NSDictionary *dic = @{@"strContent": message,
                          @"type": @(UUMessageTypeText)};
    funcView.TextViewInput.text = @"";
    [funcView changeSendBtnWithPhoto:YES];
    [self dealTheFunctionData:dic];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image
{
    NSDictionary *dic = @{@"picture": image,
                          @"type": @(UUMessageTypePicture)};
    [self dealTheFunctionData:dic];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second
{
    NSDictionary *dic = @{@"voice": voice,
                          @"strVoiceTime": [NSString stringWithFormat:@"%d",(int)second],
                          @"type": @(UUMessageTypeVoice)};
    [self dealTheFunctionData:dic];
}

- (void)dealTheFunctionData:(NSDictionary *)dic
{
    [self.chatModel addSpecifiedItem:dic];
    [self.chatTableView reloadData];
    [self tableViewScrollToBottom];
}

#pragma mark - tableView delegate & datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UUMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (cell == nil) {
        cell = [[UUMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
        cell.delegate = self;
    }
    [cell setMessageFrame:self.chatModel.dataSource[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.chatModel.dataSource[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - cellDelegate
- (void)headImageDidClick:(UUMessageCell *)cell userId:(NSString *)userId{
    // headIamgeIcon is clicked
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:cell.messageFrame.message.strName message:@"headImage clicked" delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
    [alert show];
}


@end
